//
//  PassWordViewController.m
//  Light
//
//  Created by 骁唐 on 15/10/10.
//  Copyright © 2015年 骁唐. All rights reserved.
//

#import "PassWordViewController.h"
#import "AFNetworking.h"
#import "NetworkTool.h"

@interface PassWordViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UITextField *passWordNew;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *backGround;

@end

@implementation PassWordViewController
{
    int timerNumber;
    NSTimer *timerr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    timerNumber = 60;
    self.phoneText.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.phoneText.returnKeyType = UIReturnKeyGo;
    
    self.passwordText.keyboardType = UIKeyboardTypeDefault;
    self.passwordText.returnKeyType = UIReturnKeyNext;
    self.passWordNew.keyboardType = UIKeyboardTypeDefault;
    self.passWordNew.returnKeyType = UIReturnKeyNext;
    
    self.codeText.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.codeText.returnKeyType = UIReturnKeyGo;
    
    timerr = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
    [timerr setFireDate:[NSDate distantFuture]];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//    [self.phoneText resignFirstResponder];
//    [self.passwordText resignFirstResponder];
//    [self.passWordNew resignFirstResponder];
//    [self.codeText resignFirstResponder];
    [self.view endEditing:YES];
}

#pragma mark -
#pragma mark 限制手机输入位数
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneText)
    {//手机限制11位输入
        if (range.location==11)
        {
            textField.text=[textField.text substringToIndex:10];
            return YES;
        }
    }
    return YES;
}

#pragma mark -
#pragma mark 键盘return键处理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//键盘隐藏
    if (textField == self.phoneText)
    {//手机号，如果点击return,应该直接发送验证码，但是需要验证手机号码正确性
        [self sendPhoneToGetCode];//获取验证码
    }
    else if (textField == self.passwordText)
    {
        [self.passWordNew becomeFirstResponder];
    }
    else if (textField == self.passWordNew)
    {
        [self.codeText becomeFirstResponder];
    }
    else if (textField == self.codeText)
    {//验证码，需要提交服务器，需要先验证手机号时候修改，以及两次密码是否一致。
        [self sureSubmit];//确认提交
    }
    else{}
    
    return YES;
}

#pragma mark -
#pragma mark 设置计时器
- (void)scrollTimer
{
    if (timerNumber >0) {
        [self.timeBtn setUserInteractionEnabled:NO];
        timerNumber--;
        [self.timeBtn setTitle:[NSString stringWithFormat:@"%ds",timerNumber] forState:UIControlStateNormal];
    }else{
        [timerr setFireDate:[NSDate distantFuture]];//暂停定时器
//        timerNumber = 60;
//        [self.timeBtn setTitle:[NSString stringWithFormat:@"%ds",timerNumber] forState:UIControlStateNormal];
        [self.timeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [self.timeBtn setUserInteractionEnabled:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark 设置导航返回按钮
- (IBAction)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 点击验证码
- (IBAction)codeBtnClick {
    [self sendPhoneToGetCode];
}

#pragma mark -
#pragma mark 发送手机号，获取验证码
- (void)sendPhoneToGetCode
{
    //需要先判断手机号码的正确性
    if ([TJJDefines isMobile:self.phoneText.text])
    {//如果手机号码正确
        [timerr setFireDate:[NSDate distantPast]];
        //传的参数
        NSDictionary *dic= @{@"cellPhone":self.phoneText.text};
        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
        httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
        //地址
        [httpManager POST:VERIFY_PHONE_CODE parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
            if ([retDic[@"a"] intValue] == 1) {
            }else if ([retDic[@"a"] intValue] == 0) {
                TJJALERT_VIEW(@"验证码不能重复发送");
            }else if([retDic[@"a"] intValue] == -3){
                TJJALERT_VIEW(@"该手机号码不存在");
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            TJJALERT_VIEW(ERROR_NETWORKINFO);
        }];
    }
    else
    {
        TJJALERT_VIEW(ERROR_MOBILEINFO);
    }
}

#pragma mark -
#pragma mark 确定提交按钮
- (IBAction)sureBtnClick
{
    [self sureSubmit];//提交网络请求
}

#pragma mark -
#pragma mark 确认提交，网络请求
- (void)sureSubmit
{
    //TODO:需要判断两次输入的密码是否一致，并且时候为空。还有手机号码时候同发送验证码时候的一致。
    if  ([TJJDefines isMobile:self.phoneText.text])
    {//如果手机号码格式正确
        if ([self.passWordNew.text isEqualToString:self.passwordText.text] &&  self.passwordText.text.length > 0)
        {//正确之后
            //传的参数
            NSDictionary *dic= @{@"cellPhone":self.phoneText.text,@"verification":self.codeText.text,@"password":self.passWordNew.text};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
            //地址
            [httpManager POST:USER_INFORMATION_UPDATE parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                if ([retDic[@"a"] intValue] == 1)
                {
                    [self.navigationController popViewControllerAnimated:YES];
                }
                else if ([retDic[@"a"] intValue] == 0)
                {
                    TJJALERT_VIEW(@"其他错误");
                    
                }else if([retDic[@"a"] intValue] == -1)
                {
                    TJJALERT_VIEW(@"验证码错误");
                }
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                TJJALERT_VIEW(ERROR_NETWORKINFO);
            }];
        }
        else
        {//两次输入密码不一致，请重新输入。
            TJJALERT_VIEW(ERROR_PASSWORDINFO);
        }
    }
    else
    {//手机号码格式错误
        TJJALERT_VIEW(ERROR_MOBILEINFO);
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    //SXW__标记，设置背景
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

@end
